package cn.jeeweb.modules.webservice.controller;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ff.common.constant.FFErrorCode;
import com.ff.common.util.format.JsonConvert;
import com.ff.common.web.controller.FFBaseController;
import com.ff.common.web.json.BaseReqJson;
import com.ff.common.web.json.BaseRspJson;

import cn.jeeweb.core.utils.sms.data.SmsResult;
import cn.jeeweb.modules.sms.service.ISmsSendService;
import cn.jeeweb.modules.sys.entity.User;
import cn.jeeweb.modules.sys.service.IUserService;
import cn.jeeweb.modules.sys.service.impl.PasswordService;
import cn.jeeweb.modules.webservice.SmsMessageModel;

@Controller
@RequestMapping("${api.url.prefix}/account")
public class AccountApi extends FFBaseController  
{
	@Autowired
	private IUserService userService;
	@Autowired
	PasswordService passwordService;
	
	@RequestMapping("/login")
	@ResponseBody
	public BaseRspJson<User> login(@RequestBody BaseReqJson<User> request)
	{
		BaseRspJson<User> rsp = new BaseRspJson<User>();

		User user  = getObj(request, User.class);

		
	 
		
		User old = userService.findByUsername(user.getUsername());
		if(null == old)
		{
			rsp.setErrorCode(FFErrorCode.LOGIN_INVALID);
			rsp.setMessage("用户名错误");
		}
		else
		{
			if(!old.getMd5().equals(user.getPassword()))
			{
				rsp.setErrorCode(FFErrorCode.LOGIN_INVALID);
				rsp.setMessage("密码错误");
			}
			else
			{
				String uuid = UUID.randomUUID().toString();
				old.setAppToken(uuid);
				userService.updateAllColumnById(old);
				rsp.setObj(old);
			}
		}
		
		
   		return rsp;
	}
	@RequestMapping("/logout")
	@ResponseBody
	public BaseRspJson<String> logout(@RequestBody BaseReqJson<User> request)
	{
		BaseRspJson<String> rsp = new BaseRspJson<String>();

		User user  = getObj(request, User.class);
		//User old = userService.findByUsername(user.getUsername());
 
 		
   		return rsp;
	}
	
	@Autowired
	private ISmsSendService smsSendService;
	@RequestMapping("/sendmessage")
	@ResponseBody
	public BaseRspJson<String> send(@RequestBody BaseReqJson<SmsMessageModel> request)
	{
		BaseRspJson<String> rsp = new BaseRspJson<String>();

		SmsMessageModel msg  = getObj(request, SmsMessageModel.class);
		//User old = userService.findByUsername(user.getUsername());
		SmsResult smsResult = null;
		smsResult = smsSendService.sendSyncSmsByCode(msg.getPhone(), msg.getTemplateCode(), JsonConvert.ObjectToJson(msg.getContent()));
		if (!smsResult.isSuccess()) {
			rsp.setErrorCode(FFErrorCode.FAIL);
			rsp.setMessage(smsResult.getMsg());
		}
   		return rsp;
	}
}
